<?php

/**
 * Description of PatientCardPresenter
 *
 * @author Pavel Homolka
 */

namespace AdminModule;

use Entities\Person\Patient,
    Entities\Person\AbstractAddress,
    Nette\Application\UI;

class PatientCardPresenter extends BasePresenter {

    protected function startup() {
        parent::startup();
        
        $this->template->mainMenu = array(
            'Vyhledat kartu' => 'PatientCard:find',
            'Karta pacienta' => 'PatientCard:view',
            'Úprava karty' => 'PatientCard:edit',
            'Nová karta' => 'PatientCard:new',
        );
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO FIND CARD ///////////////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionFind() {
        $form = $this->getComponent('findPatient');
        $form->addGroup()->setOption('container', 'button');
        $form->addSubmit('find', 'Vyhledat');
        $form->onSuccess[] = callback($this, 'findFormSubmitted');
    }

    public function findFormSubmitted($form) {
        $query = $this->entityManager->createQueryBuilder();
        $query->select('patient')->from('Model\Entities\Patient', 'patient');
        foreach ($form->getValues() as $key => $value) {
            if (!empty($value)) {
                $query->andWhere('patient.' . $key . ' = ' . ':' . $key)
                        ->setParameter($key, $value);
            }
        }
        $query = $query->getQuery()->getArrayResult();
        //vyprazdneni session
        $this->context->patientSession->removeSearchResult();
        //naplneni novym vysledkem
        foreach ($query as $patient) {
            $this->context->patientSession->setSearchResult($patient['id'], $patient);
        }
        $this->template->resultQuery = $query;
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO CARD PATIENT ////////////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionView($patientId) {
        $this->template->subMenu = array(
            'Rodinná anamnéza' => 'familyAnamnesis',
            'Osobní anamnéza' => 'personalAnamnesis',
            'Záchvatová anamnéza' => 'seizureAnamnesis',
        );
        $this->template->resultQuery = $this->context->patientSession->getSearchResult();
        if (!empty($patientId)) {
            $this->context->patientSession->setCurentPatient($patientId);
        }
        dump('ID curent patient: ' . $this->context->patientSession->getCurentPatient());
    }

    public function renderView($patientId) {
        if (!empty($patientId)) {
            $patient = $this->entityManager->getRepository('Model\Entities\Patient')->find($patientId);
        } elseif ($this->context->patientSession->getCurentPatient() != NULL) {
            $patient = $this->entityManager
                    ->getRepository('Model\Entities\Patient')
                    ->find($this->context->patientSession->getCurentPatient());
        } else {
            $this->flashMessage('Není vybrán žádný pacient.');
            $this->redirect('find');
        }
        $form = $this->getComponent('findPatient')->setDefaults(array(
            'identificationNumber' => $patient->getIdentificationNumber(),
            'surName' => $patient->getSurName(),
            'firstName' => $patient->getFirstName(),
            'birthDate' => $patient->getBirthDate(),
            'gender' => $patient->getGender(),
            'nickName' => $patient->getNickName(),
            'street' => $patient->getStreet(),
            'city' => $patient->getCity(),
            'zip' => $patient->getZip(),
            'state' => $patient->getState(),
            'homePhone' => $patient->getHomePhone(),
            'mobile' => $patient->getMobilePhone(),
            'mail' => $patient->getMail(),
                ));
        foreach ($form->getComponents() as $component) {
            $component->setDisabled();
        }
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO FAMILY ANAMNESIS ////////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionFamilyAnamnesis() {
        $this->template->subMenu = array(
            'Rodinná anamnéza' => 'familyAnamnesis',
            'Osobní anamnéza' => 'personalAnamnesis',
            'Záchvatová anamnéza' => 'seizureAnamnesis',
        );
        $this->template->resultQuery = $this->context->patientSession->getSearchResult();
    }

    public function renderFamilyAnamnesis() {
        //nacteni vybraneho pacienta
        $patient = $this->entityManager->find('Model\Entities\Patient', $this->context->patientSession->getCurentPatient());

        //vyplneni ifentifikacnich a kontaktnich udaju
        $form = $this->getComponent('findPatient')->setDefaults(array(
            'identificationNumber' => $patient->getIdentificationNumber(),
            'surName' => $patient->getSurName(),
            'firstName' => $patient->getFirstName(),
            'birthDate' => $patient->getBirthDate(),
            'gender' => $patient->getGender(),
            'nickName' => $patient->getNickName(),
            'street' => $patient->getStreet(),
            'city' => $patient->getCity(),
            'zip' => $patient->getZip(),
            'state' => $patient->getState(),
            'homePhone' => $patient->getHomePhone(),
            'mobile' => $patient->getMobilePhone(),
            'mail' => $patient->getMail(),
                ));
        foreach ($form->getComponents() as $component) {
            $component->setDisabled();
        }

        //nacteni anamnezi 
        try {

            $familyAnamnesisForm = $this->getComponent('familyAnamnesis')->setDefaults(array(
                'annotations' => $patient->getFamilyAnamnesis()->getAnnotations(),
                'nonCNScomorbidity' => $patient->getFamilyAnamnesis()->getNonCNScomorbidity(),
                    ));
            $this->template->familyAnamnesis = TRUE;
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Rodiná anamnéza nenalezena.');
            $this->template->familyAnamnesis = NULL;
        }
        $this->setView('anamnesis');
    }

    public function createComponentFamilyAnamnesis() {
        $form = new UI\Form();
        $form->addGroup('Rodinná anamnéza');
        $form->addTextArea('annotations', 'Komentáře');
        $form->addTextArea('nonCNScomorbidity', 'Non - CNS komorbidita');
        return $form;
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO PERSONAL ANAMNESIS //////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionPersonalAnamnesis() {
        $this->template->subMenu = array(
            'Rodinná anamnéza' => 'familyAnamnesis',
            'Osobní anamnéza' => 'personalAnamnesis',
            'Záchvatová anamnéza' => 'seizureAnamnesis',
        );
        $this->template->resultQuery = $this->context->patientSession->getSearchResult();
    }

    public function renderPersonalAnamnesis() {
        $patient = $this->entityManager->find('Model\Entities\Patient', $this->context->patientSession->getCurentPatient());
        $form = $this->getComponent('findPatient')->setDefaults(array(
            'identificationNumber' => $patient->getIdentificationNumber(),
            'surName' => $patient->getSurName(),
            'firstName' => $patient->getFirstName(),
            'birthDate' => $patient->getBirthDate(),
            'gender' => $patient->getGender(),
            'nickName' => $patient->getNickName(),
            'street' => $patient->getStreet(),
            'city' => $patient->getCity(),
            'zip' => $patient->getZip(),
            'state' => $patient->getState(),
            'homePhone' => $patient->getHomePhone(),
            'mobile' => $patient->getMobilePhone(),
            'mail' => $patient->getMail(),
                ));
        foreach ($form->getComponents() as $component) {
            $component->setDisabled();
        }

        try {
            $this->getComponent('personalAnamnesis')->setDefaults(array(
                'epilepsyInFamily' => $patient->getPersonalAnamnesis()->getEpilepsyInFamily(),
                'prePerinatalRisks' => $patient->getPersonalAnamnesis()->getPrePerinatalRisks(),
                'febrileSeizures' => $patient->getPersonalAnamnesis()->getFebrileSeizures(),
                'CNSinflammation' => $patient->getPersonalAnamnesis()->getCNSinflammation(),
                'CNStrauma' => $patient->getPersonalAnamnesis()->getCNStrauma(),
                'CNSsurgery' => $patient->getPersonalAnamnesis()->getCNSsurgery(),
                'earlyPMDretardation' => $patient->getPersonalAnamnesis()->getEarlyPMDretardation(),
            ));
            $this->template->personalAnamnesis = TRUE;
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Osobní anamnéza nenalezena.');
            $this->template->personalAnamnesis = NULL;
        }
        $this->setView('anamnesis');
    }

    public function createComponentPersonalAnamnesis() {
        $form = new UI\Form();

        $form->addGroup('Osobní anamnéza');
        $form->addCheckbox('epilepsyInFamily', 'Epilepsie v rodině');
        $form->addCheckbox('prePerinatalRisks', 'Pre/Perinatální rizika');
        $form->addCheckbox('febrileSeizures', 'Febrilní křeče');
        $form->addCheckbox('CNSinflammation', 'Zánět CNS');
        $form->addCheckbox('CNStrauma', 'Úraz CNS');
        $form->addCheckbox('CNSsurgery', 'Operace CNS');
        $form->addCheckbox('earlyPMDretardation', 'Časná PMD retardace');

        return $form;
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO SEIZURE ANAMNESIS ///////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionSeizureAnamnesis() {
        $this->template->subMenu = array(
            'Rodinná anamnéza' => 'familyAnamnesis',
            'Osobní anamnéza' => 'personalAnamnesis',
            'Záchvatová anamnéza' => 'seizureAnamnesis',
        );
        $this->template->resultQuery = $this->context->patientSession->getSearchResult();
    }

    public function renderSeizureAnamnesis() {
        $patient = $this->entityManager->find('Model\Entities\Patient', $this->context->patientSession->getCurentPatient());
        $form = $this->getComponent('findPatient')->setDefaults(array(
            'identificationNumber' => $patient->getIdentificationNumber(),
            'surName' => $patient->getSurName(),
            'firstName' => $patient->getFirstName(),
            'birthDate' => $patient->getBirthDate(),
            'gender' => $patient->getGender(),
            'nickName' => $patient->getNickName(),
            'street' => $patient->getStreet(),
            'city' => $patient->getCity(),
            'zip' => $patient->getZip(),
            'state' => $patient->getState(),
            'homePhone' => $patient->getHomePhone(),
            'mobile' => $patient->getMobilePhone(),
            'mail' => $patient->getMail(),
                ));
        foreach ($form->getComponents() as $component) {
            $component->setDisabled();
        }

        try {
            $syndrom = $this->entityManager->find('Model\Entities\Syndrom', $patient->getSeizureAnamnesis()->getSpecificSyndrome());
            $form = $this->getComponent('seizureAnamnesis')->setDefaults(array(
                'ageAtStartOfEpilepsy' => $patient->getSeizureAnamnesis()->getAgeAtStartOfEpilepsy(),
                'firstSZwithFever' => $patient->getSeizureAnamnesis()->getFirstSZwithFever(),
                'infantileSpasms' => $patient->getSeizureAnamnesis()->getInfantileSpasms(),
                'syndrom' => $syndrom == NULL ? NULL : $syndrom->getCzechName(),
                    ));
            $this->template->seizureAnamnesis = TRUE;
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Záchvatová anamnéza nenalezena.');
            $this->template->seizureAnamnesis = NULL;
        }
        $this->setView('anamnesis');
    }

    public function createComponentSeizureAnamnesis() {
        $form = new UI\Form();
        $form->addGroup('Záchvatová anamnéza');
        $form->addText('ageAtStartOfEpilepsy', 'Věk při začátku epilepsie (roky)');
        $form->addCheckbox('firstSZwithFever', 'První záchvat s horečkou');
        $form->addCheckbox('infantileSpasms', 'Infaltilní spasmy');
//	$form->addSelect('syndrom', 'Specifický syndrom', $syndroms);
        $form->addText('syndrom', 'Specifický syndrom');
        return $form;
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO EDIT ////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
    public function actionEdit() {
        if ($this->context->patientSession->getCurentPatient() == NULL) {
            $this->flashMessage('Není vybrán žádný pacient.');
            $this->redirect('find');
        }
        $patientForm = $this->getComponent('patientForm');
        $patientForm->addSubmit('save', 'Ulož');
        $patientForm->onSuccess[] = callback($this, 'patientEditFormSubmitted');
    }

    public function renderEdit() {
        $patient = $this->entityManager
                ->getRepository('Model\Entities\Patient')
                ->find($this->context->patientSession->getCurentPatient());

        $patientForm = $this->getComponent('patientForm')->setDefaults(array(
            'identificationNumber' => $patient->getIdentificationNumber(),
            'surName' => $patient->getSurName(),
            'firstName' => $patient->getFirstName(),
            'birthDate' => $patient->getBirthDate(),
            'gender' => $patient->getGender(),
            'nickName' => $patient->getNickName(),
            'street' => $patient->getStreet(),
            'city' => $patient->getCity(),
            'zip' => $patient->getZip(),
            'state' => $patient->getState(),
            'homePhone' => $patient->getHomePhone(),
            'mobile' => $patient->getMobilePhone(),
            'mail' => $patient->getMail(),
                ));

        try {
            $patientForm = $this->getComponent('patientForm')->setDefaults(array(
                'annotations' => $patient->getFamilyAnamnesis()->getAnnotations(),
                'nonCNScomorbidity' => $patient->getFamilyAnamnesis()->getNonCNScomorbidity(),
                    ));
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Rodiná anamnéza nenalezena.');
        }

        try {
            $patientForm = $this->getComponent('patientForm')->setDefaults(array(
                'epilepsyInFamily' => $patient->getPersonalAnamnesis()->getEpilepsyInFamily(),
                'prePerinatalRisks' => $patient->getPersonalAnamnesis()->getPrePerinatalRisks(),
                'febrileSeizures' => $patient->getPersonalAnamnesis()->getFebrileSeizures(),
                'CNSinflammation' => $patient->getPersonalAnamnesis()->getCNSinflammation(),
                'CNStrauma' => $patient->getPersonalAnamnesis()->getCNStrauma(),
                'CNSsurgery' => $patient->getPersonalAnamnesis()->getCNSsurgery(),
                'earlyPMDretardation' => $patient->getPersonalAnamnesis()->getEarlyPMDretardation(),
                    ));
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Osobní anamnéza nenalezena.');
        }


        try {
            $seizureAnamnesisForm = $this->getComponent('patientForm')->setDefaults(array(
                'ageAtStartOfEpilepsy' => $patient->getSeizureAnamnesis()->getAgeAtStartOfEpilepsy(),
                'firstSZwithFever' => $patient->getSeizureAnamnesis()->getFirstSZwithFever(),
                'infantileSpasms' => $patient->getSeizureAnamnesis()->getInfantileSpasms(),
                    ));
            $syndromCurrent = $this->entityManager->find('Model\Entities\Syndrom', $patient->getSeizureAnamnesis()->getSpecificSyndrome());
            $seizureAnamnesisForm->getComponent('syndrom')->setDefaultValue($syndromCurrent == NULL ? NULL : $syndromCurrent->getId());
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Záchvatová anamnéza nenalezena.');
        }
    }

    public function patientEditFormSubmitted($form) {
        $values = $form->getValues();
        $patient = $this->entityManager
                ->getRepository('Model\Entities\Patient')
                ->find($this->context->patientSession->getCurentPatient());
        try {
            $patient->setIdentificationNumber($values['identificationNumber']);
            $patient->setSurName($values['surName']);
            $patient->setFirstName($values['firstName']);
            $patient->setBirthDate($values['birthDate']);
            $patient->setGender($values['gender']);
            $patient->setNickName($values['nickName']);
            $patient->setStreet($values['street']);
            $patient->setCity($values['city']);
            $patient->setZip($values['zip']);
            $patient->setState($values['state']);
            $patient->setHomePhone($values['homePhone']);
            $patient->setMobilePhone($values['mobilePhone']);
            $patient->setMail($values['mail']);

            $patient->getFamilyAnamnesis()->setAnnotations($values['annotations']);
            $patient->getFamilyAnamnesis()->setNonCNScomorbidity($values['nonCNScomorbidity']);

            $patient->getPersonalAnamnesis()->setEpilepsyInFamily($values['epilepsyInFamily']);
            $patient->getPersonalAnamnesis()->setPrePerinatalRisks($values['prePerinatalRisks']);
            $patient->getPersonalAnamnesis()->setFebrileSeizures($values['febrileSeizures']);
            $patient->getPersonalAnamnesis()->setCNSinflammation($values['CNSinflammation']);
            $patient->getPersonalAnamnesis()->setCNStrauma($values['CNStrauma']);
            $patient->getPersonalAnamnesis()->setCNSsurgery($values['CNSsurgery']);
            $patient->getPersonalAnamnesis()->setEarlyPMDretardation($values['earlyPMDretardation']);

            $patient->getSeizureAnamnesis()->setAgeAtStartOfEpilepsy($values['ageAtStartOfEpilepsy']);
            $patient->getSeizureAnamnesis()->setFirstSZwithFever($values['firstSZwithFever']);
            $patient->getSeizureAnamnesis()->setInfantileSpasms($values['infantileSpasms']);
            //$syndrom = $this->entityManager->find('Model\Entities\Syndrom', $values['syndrom']);
            $patient->getSeizureAnamnesis()->setSpecificSyndrome($values['syndrom']);
        } catch (\Doctrine\ORM\EntityNotFoundException $e) {
            $this->flashMessage('Na odstranění chyby se pracuje.');
        }
        $this->entityManager->flush();
        $this->flashMessage('Záznam editován.');
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////// METODY PRO NEW /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////

    public function actionNew() {
        $patientForm = $this->getComponent('patientForm');
        $patientForm->addSubmit('save', 'Ulož');
        $patientForm->onSuccess[] = callback($this, 'patientNewFormSubmitted');
    }

    public function patientNewFormSubmitted($form) {
        $values = $form->getValues();
        $patient = new \Model\Entities\Patient();
        $familyAnamnesis = new \Model\Entities\FamilyAnamnesis();
        $personalAnamnesis = new \Model\Entities\PersonalAnamnesis();
        $seizureAnamnesis = new \Model\Entities\SeizureAnamnesis();

        $patient->setIdentificationNumber($values['identificationNumber']);
        $patient->setSurName($values['surName']);
        $patient->setFirstName($values['firstName']);
        $patient->setBirthDate($values['birthDate']);
        $patient->setGender($values['gender']);
        $patient->setNickName($values['nickName']);
        $patient->setStreet($values['street']);
        $patient->setCity($values['city']);
        $patient->setZip($values['zip']);
        $patient->setState($values['state']);
        $patient->setHomePhone($values['homePhone']);
        $patient->setMobilePhone($values['mobilePhone']);
        $patient->setMail($values['mail']);

        $familyAnamnesis->setAnnotations($values['annotations']);
        $familyAnamnesis->setNonCNScomorbidity($values['nonCNScomorbidity']);
        //$patient->setFamilyAnamnesis($familyAnamnesis);

        $personalAnamnesis->setEpilepsyInFamily($values['epilepsyInFamily']);
        $personalAnamnesis->setPrePerinatalRisks($values['prePerinatalRisks']);
        $personalAnamnesis->setFebrileSeizures($values['febrileSeizures']);
        $personalAnamnesis->setCNSinflammation($values['CNSinflammation']);
        $personalAnamnesis->setCNStrauma($values['CNStrauma']);
        $personalAnamnesis->setCNSsurgery($values['CNSsurgery']);
        $personalAnamnesis->setEarlyPMDretardation($values['earlyPMDretardation']);
        //$patient->setPersonalAnamnesis($personalAnamnesis);

        $seizureAnamnesis->setAgeAtStartOfEpilepsy($values['ageAtStartOfEpilepsy']);
        $seizureAnamnesis->setFirstSZwithFever($values['firstSZwithFever']);
        $seizureAnamnesis->setInfantileSpasms($values['infantileSpasms']);
        //$syndrom = $this->entityManager->find('Model\Entities\Syndrom', $values['syndrom']);
        $seizureAnamnesis->setSpecificSyndrome($values['syndrom']);
        $patient->setSeizureAnamnesis($seizureAnamnesis);

        $this->entityManager->persist($patient);
        $this->entityManager->persist($familyAnamnesis);
        $this->entityManager->persist($personalAnamnesis);
        $this->entityManager->persist($seizureAnamnesis);
        $this->entityManager->flush();
        //$this->context->patientSession->setCurentPatient($patientId);
    }

////////////////////////////////////////////////////////////////////////////
/////////////////////////// KOMPONENTY /////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
    public function createComponentFindPatient() {
        $form = new \Nette\Application\UI\Form();
        $form->addGroup('Identifikační údaje');
        $form->addText('identificationNumber', 'Rodné číslo:');
        $form->addText('surName', 'Příjmení:');
        $form->addText('firstName', 'Jméno:');
        $form->addText('birthDate', 'Datum narozeni:');
        $form->addText('gender', 'Pohlaví:');
        $form->addText('nickName', 'Přezdívka:');
        $form->addText('neurolog', 'Neurolog:');

        $form->addGroup('Kontaktní údaje');
        $form->addText('street', 'Ulice:');
        $form->addText('city', 'Město:');
        $form->addText('zip', 'PSČ:');
        $form->addText('state', 'Stát:');
        $form->addText('homePhone', 'Telefon domů:');
        $form->addText('mobilePhone', 'Mobilní telefon:');
        $form->addText('mail', 'E-mail:');

        return $form;
    }

    public function createComponentPatientForm() {
        $form = new \Nette\Application\UI\Form();

        foreach ($this->entityManager->getRepository('Model\Entities\Syndrom')->findAll() as $syndrom) {
            $syndroms[$syndrom->getId()] = $syndrom->getCzechName();
        }

        $form->addGroup('Identifikační údaje');
        $form->addText('identificationNumber', 'Rodné číslo:');
        $form->addText('surName', 'Příjmení:');
        $form->addText('firstName', 'Jméno:');
        $form->addText('birthDate', 'Datum narozeni:');
        $form->addText('gender', 'Pohlaví:');
        $form->addText('nickName', 'Přezdívka:');
        $form->addText('neurolog', 'Neurolog:');

        $form->addGroup('Kontaktní údaje');
        $form->addText('street', 'Ulice:');
        $form->addText('city', 'Město:');
        $form->addText('zip', 'PSČ:');
        $form->addText('state', 'Stát:');
        $form->addText('homePhone', 'Telefon domů:');
        $form->addText('mobilePhone', 'Mobilní telefon:');
        $form->addText('mail', 'E-mail:');

        $form->addGroup('Rodinná anamnéza');
        $form->addTextArea('annotations', 'Komentáře');
        $form->addTextArea('nonCNScomorbidity', 'Non - CNS komorbidita');

        $form->addGroup('Osobní anamnéza');
        $form->addCheckbox('epilepsyInFamily', 'Epilepsie v rodině');
        $form->addCheckbox('prePerinatalRisks', 'Pre/Perinatální rizika');
        $form->addCheckbox('febrileSeizures', 'Febrilní křeče');
        $form->addCheckbox('CNSinflammation', 'Zánět CNS');
        $form->addCheckbox('CNStrauma', 'Úraz CNS');
        $form->addCheckbox('CNSsurgery', 'Operace CNS');
        $form->addCheckbox('earlyPMDretardation', 'Časná PMD retardace');

        $form->addGroup('Záchvatová anamnéza');
        $form->addText('ageAtStartOfEpilepsy', 'Věk při začátku epilepsie (roky)');
        $form->addCheckbox('firstSZwithFever', 'První záchvat s horečkou');
        $form->addCheckbox('infantileSpasms', 'Infaltilní spasmy');
        $form->addSelect('syndrom', 'Specifický syndrom', $syndroms);

        return $form;
    }

}